<?php

namespace app\index\controller;

use think\Controller;
use think\Db;
use think\Request;
use think\Url;
use think\Session;
use think\Cookie;
use My\PHPMailer;
use CCP\REST;
use CCP\stdClass;
use My\Redis;

class Login extends Controller
{


    public function index()
    {
        return view('login/index',['CSS_PATH'=>config('index_css'),
            'JS_PATH'=>config('index_js'),
            'ICON_PATH'=>config('index_icon'),
            'IMG_PATH'=>config('index_img'),
            'index_name'=>Session::get('index_name'),
            'index_id'=>Session::get('index_id'),
        ]);
    }

    public function doLogin(Request $request)
    {
    	$post = $request->post();
        // var_dump($post);
    	$check = key_exists('check',$post)?'1':'0';
    	// 验证用户名密码一致
            $email = $post['UserameE'];
    		$tel = $post['Userame'];
    		$pass = md5($post['Password']);
            $em = $post['emlogin'];
            if($em == 1){
    		  $data = DB::name('user')->where(['tel'=>$tel, 'password'=>$pass])->find();
              if(!$data){
                $this->error('登录失败,请重新登录',url('index/login/index'));
              }
              $name = $data['name'];
              $id = $data['id'];
            }else if($em == 2){
                // var_dump($email);
                $id = (DB::name('user_info')-> where(['email'=> $email])->select())[0]['id'];
                if(!$id){
                    $this->error('登录失败,请重新登录',url('index/login/index'));
                }else{
                    $data = DB::name('ui_id') 
                            -> alias('uii')
                            -> where(['uii.user_info_id'=>$id])
                            -> join('gqx_user u','u.id = uii.user_id')
                            -> select();
                    // var_dump($data);die;
                    if(!$data){
                        $this->error('登录失败,请重新登录',url('index/login/index'));
                    }else if($data[0]['password'] != $pass){
                        $this->error('登录失败,请重新登录',url('index/login/index'));
                    }
                    $name = $data[0]['name'];
                    $id = $data[0]['user_id'];
                }
            }
			if($id){
    			if($check){
    				Session::set('index_name',$name);
    				Cookie::set('index_name', $name, 86400*7);
                    Session::set('index_id',$id);
                    Cookie::set('index_id', $id, 86400*7);
                    Redis::set('token',$name,86400*7);
    			}else{
    				Session::set('index_name',$name);
                    Session::set('index_id',$id);
    			}
                return $this->redirect('index/index/index');

			}else{
				return $this->error('登录失败');
			}
    }


    public function info($id = '')
    {
        if (empty(Session::get('index_id')) || Session::get('index_id')!=$id){
            return $this->redirect('index/login/index');
        }
       $user = DB::name('user')->where(['id'=>$id])->select();
       $uid = (DB::name('ui_id')->where(['user_id'=>$id])->select())[0]['user_info_id'];
       $userinfo = DB::name('user_info')->where(['id'=>$uid])->select();
       $data = array_merge($user, $userinfo);
       $namelist = Db::name('category')->select();
       $answer = DB::name('answer')->where(['uid'=>$id])->select();
       $answer_likes = DB::name('answer_likes')
       -> alias('al')
       -> where(['al.uid'=>$id])
       -> join('gqx_answer a','a.id = al.aid')
       ->select();
       return view('login/userinfo',['CSS_PATH'=>config('index_css'),
            'JS_PATH'=>config('index_js'),
            'ICON_PATH'=>config('index_icon'),
            'IMG_PATH'=>config('index_img'),
            'index_name'=>Session::get('index_name'),
            'index_id'=>Session::get('index_id'),
            'namelist'=>$namelist,
            'data'=>$data, 
            'answer'=>$answer, 
            'answer_likes'=>$answer_likes
        ]);
    }

    public function logout()
    {
        Session::delete('index_name');
        Cookie::delete('index_name');
        Session::delete('index_id');
        Cookie::delete('index_id');
        session(null);
        cookie(null, 'think_');
        // 需要完善,删除购物车信息
        return $this->redirect('index/index/index', ['cate_id' => 2]);
    }

    public function editInfo($id = '')
    {
        if (empty(Session::get('index_id'))|| Session::get('index_id')!=$id){
            return $this->redirect('index/login/index');
        }
        $user = DB::name('user')->where(['id'=>$id])->select();
        $uid = (DB::name('ui_id')->where(['user_id'=>$id])->select())[0]['user_info_id'];
        $data = DB::name('user_info')->where(['id'=>$uid])->select();
        $namelist = Db::name('category')->select();
        return view('login/editinfo',['CSS_PATH'=>config('index_css'),
            'JS_PATH'=>config('index_js'),
            'ICON_PATH'=>config('index_icon'),
            'IMG_PATH'=>config('index_img'),
            'index_name'=>Session::get('index_name'),
            'index_id'=>Session::get('index_id'),
            'namelist'=>$namelist,
            'data'=>$data[0]
        ]);
    }

    public function doEditInfo(Request $request)
    {
        if (empty(Session::get('index_id'))){
            return $this->redirect('index/login/index');
        }
        $post = $request->post();
        unset($post['submit']);
        $id = Session::get('index_id');
        $uid = (DB::name('ui_id')->where('user_id ='.$id)->select())[0]['user_info_id'];
        foreach ($post as $k => $v) {
            if($v === ''){
                unset($post[$k]);
            }
        }
        $data = DB::name('user_info')->where(['id'=>$uid])->update($post);
        return $this->success('修改成功',url('index/login/info','id='.$id));
    }

    public function editPass()
    {
        if (empty(Session::get('index_id'))){
            return $this->redirect('index/login/index');
        }
        $namelist = Db::name('category')->select();
        return view('login/editpass',['CSS_PATH'=>config('index_css'),
            'JS_PATH'=>config('index_js'),
            'ICON_PATH'=>config('index_icon'),
            'IMG_PATH'=>config('index_img'),
            'index_name'=>Session::get('index_name'),
            'index_id'=>Session::get('index_id'),
            'namelist'=>$namelist
        ]);
    }

    public function doEditPass(Request $request)
    {
        if (empty(Session::get('index_id'))){
            return $this->redirect('index/login/index');
        }
        $post = $request->post();
        $p = md5($post['password']);
        $id = Session::get('index_id');
        DB::name('user')->where('id='.$id)->update(['password'=>$p]);
        return $this->success('修改成功',url('index/login/info','id='.$id));
    }

    public function photo()
    {
        if (empty(Session::get('index_id'))){
            return $this->redirect('index/login/index');
        }
        $id = Session::get('index_id');
        $uid = (DB::name('ui_id')->where('user_id='.$id)->select())[0]['user_info_id'];
        $file = request()->file('uploadfile');
        $info = $file->move(ROOT_PATH . 'public' . DS . '/static/upload');
        if($info){
        // 输出 文件名
        $photo = $info->getSavename();
        $p = str_replace('\\', '/', $photo);
        DB::name('user_info')->where('id='.$uid)->update(['photo'=>$p]);
        return $this->success('修改成功',url('index/login/info','id='.$id));
        }else{
        // 上传失败获取错误信息
        echo $file->getError();
        return $this->success('修改失败',url('index/login/info','id='.$id));
        }
    }

    public function sendEmail(Request $request)
    {
        if (empty(Session::get('index_id'))){
            return $this->redirect('index/login/index');
        }
        $m = $request -> post();
        $ma = $m['email'];
        $na = strstr($ma,'@',true);
        $num = rand();
        // $_SESSION['register']['email'] = $ma;
        Session::set('rEmail',$ma);
        // $_SESSION['register']['etemp'] = $num;
        Session::set('reTemp',$num);
        // Request::instance()->module('class.phpmailer.php');
        // require("/module/class.phpmailer.php"); //这个是一个smtp的php文档，网上可以下载得到
        $mail = new PHPMailer(); //建立邮件发送类
        $mail->CharSet = "UTF-8";
        $address ="2256169434@qq.com";
        $mail->IsSMTP(); // 使用SMTP方式发送
        $mail->Host = "smtp.qq.com"; // 您的企业邮局域名
        $mail->SMTPAuth = true; // 启用SMTP验证功能
        $mail->Username = "2256169434@qq.com"; // 邮局用户名(请填写完整的email地址)
        $mail->Password = "grqgeskxmltwdjje"; // 邮局密码授权码
        $mail->Port=25; // 大多数端口
        $mail->From = "2256169434@qq.com"; //邮件发送者email地址
        $mail->FromName = "GQX问答网 赶快学";// 在闲聊 100%垃圾箱 匹配邮箱名 
        $mail->AddAddress($ma, $na);//收件人地址，可以替换成任何想要接收邮件的email信箱,格式是AddAddress("收件人email","收件人姓名")
        //$mail->AddReplyTo("", "");

        //$mail->AddAttachment("/var/tmp/file.tar.gz"); // 添加附件
        $mail->IsHTML(true); // set email format to HTML //是否使用HTML格式

        $mail->Subject = "GQX问答网 请接收您的验证码"; //邮件标题
        $mail->Body = $num; //邮件内容，上面设置HTML，则可以是HTML
        if(!$mail->Send())
        {
            return $mail->ErrorInfo;
            exit;
        }else{
        return 'ml';
        }
    }

    public function sendMobile(Request $request)
    {   
        $m = $request -> post();
        $mobile = $m['tel'];
        //判断手机号
        // $_SESSION['register']['tel'] = $mobile;
        Session::set('rTel',$mobile);
        $temp = rand(100000,999999);
        // $_SESSION['register']['temp'] = $temp;
        Session::set('rTemp',$temp);
        // sendTemplateSMS($tel,array($temp,10),"1");
        // sendTemplateSMS($tel,array($temp,10),"1");
        // return '已发送 请查收';
        $stdClass = new stdClass;
        $data = $stdClass->sendTemplateSMS($mobile,array($temp,10),"1");
        return $data;

    }

    public function register(Request $request)
    {
        $post = $request->post();
        $eom = $post['eom'];
        $name = $post['Name'];
        $email = $post['Email'];
        $cEmail = $post['cEmail'];
        $Tel = $post['Tel'];
        $cTel = $post['cTel'];
        $Password = $post['Password'];
        // var_dump($post);
        // var_dump(Request::instance()->session());

        // var_dump($rEmail,$reTemp,$rTel,$rTemp);
        if($eom == 1)
        {
            $rTel = Session::get('rTel');
            $rTemp = strval(Session::get('rTemp'));
            if($cTel != $rTemp){
                var_dump($cTel,$rTemp);
                die;
                // $this->error('注册失败!');
            }
            // 验证方式为手机
            $user = ['name'=>$name, 'tel'=>$Tel, 'password'=> md5($Password), 'status'=>'1'];
            $info = ['addtime'=>time()];
        }else if($eom == 2){
            $rEmail = Session::get('rEmail');
            $reTemp = strval(Session::get('reTemp'));
            // var_dump($rEmail,$reTemp,$cEmail);die;
                if($cEmail != $reTemp){
                    var_dump($cEmail,$reTemp);die;
                    // $this->error('注册失败!');
                }
            $user = ['name'=>$name, 'password'=> md5($Password), 'status'=>'1'];
            $info = ['email'=>$email, 'addtime'=>time()];
        }
            $iUser = DB::name('user')->insertGetId($user);
            $iInfo = DB::name('user_info')->insertGetId($info);
            $uiid = DB::name('ui_id')->insert(['user_id'=>$iUser, 'user_info_id'=>$iInfo]);
            if($iUser && $iInfo && $uiid){
                $this->success('注册成功!');
            }else{
                $this->error('注册失败!');
            }         
    }



}

